<template>
  <div class="app-container">
    <div class="container-header">
      <div class="container-header-left">
        <el-form inline>
          <!-- 表单元素 -->
          <el-form-item>
            <el-input
              v-model="searchContent"
              clearable
              placeholder="请输入内容"
            />
          </el-form-item>
          <!-- 查询与情况的按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="getCourses(1)"
              >查询</el-button
            >
          </el-form-item>

          <el-form-item>
            <el-cascader
              size="large"
              :options="options"
              v-model="selectedOptions"
            >
            </el-cascader>
          </el-form-item>
          <!-- <el-button type="primary" @click="">考场切换</el-button> -->
          <el-button type="primary" @click="getCourses(1)">课程查询</el-button>
          <el-button type="primary" @click="addOrChangeCourseHandle"
            >课程添加</el-button
          >
        </el-form>
      </div>
      <div class="container-header-right">
        <!-- <el-form inline>
          <el-form-item>
            <el-cascader
              size="large"
              :options="options"
              v-model="selectedOptions"
            >
            </el-cascader>
          </el-form-item>
          <el-button type="primary" @click="getCourses(1)">课程查询</el-button>
          <el-button type="primary" @click="addOrChangeCourseHandle"
            >课程添加</el-button
          >
        </el-form> -->
      </div>
    </div>

    <!-- table表格：展示用户信息的地方 -->
    <el-table border stripe v-loading="listLoading" :data="courses">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="roomName" label="考场" width="150" />
      <el-table-column prop="coursesName" label="课程名称" width="150" />
      <el-table-column prop="label" label="课程标题" width="150" />
      <el-table-column prop="money" label="金额" width="150" />
      <el-table-column prop="coverUrl" label="封面" width="150">
        <template slot-scope="{ row }">
          <img
            :src="row.coverUrl || require('@/assets/image/mrtx.png')"
            alt="封面"
            style="width: 80px; height: 80px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="coursesDesc" label="描述" />
      <el-table-column prop="freeTag" label="是否免费">
        <template slot-scope="{ row }">
          <div>{{ row.freeTag == "0" ? "付费" : "免费" }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="effectiveTime" label="有效时长"> </el-table-column>
      <el-table-column label="操作" align="center" width="250">
        <template slot-scope="{ row }">
          <HintButton
            style="margin-left: 10px"
            slot="reference"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            title="课程修改"
            @click="addOrChangeCourseHandle(row)"
          />
          <HintButton
            style="margin-left: 10px"
            slot="reference"
            type="primary"
            size="mini"
            icon="el-icon-video-camera-solid"
            title="视频列表"
            @click="routerGo(row)"
          />
          <el-popconfirm
            :title="`确定删除课程 ${row.coursesName} 吗?`"
            @confirm="removeCourse(row.id)"
          >
            <HintButton
              style="margin-left: 10px"
              slot="reference"
              type="danger"
              size="mini"
              icon="el-icon-delete"
              title="课程删除"
            />
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      :current-page="current"
      :total="total"
      :page-size="count"
      :page-sizes="[4, 10, 20, 30, 40, 50]"
      style="padding: 20px 0"
      layout="prev, pager, next, jumper, ->, sizes, total"
      @current-change="getCourses"
      @size-change="handleSizeChange"
    />
    <el-drawer
      size="50%"
      :title="addCourseFormTitle"
      :visible.sync="addCourseVisible"
      :before-close="addCourseCancel"
    >
      <el-form
        ref="addCourseForm"
        :model="addCourseForm"
        :rules="addCourseRules"
        v-loading="formLoading"
        label-width="120px"
      >
        <el-form-item label="考场地址：" prop="addCourseAreaCode">
          <el-cascader
            size="large"
            :options="options"
            v-model="addCourseForm.addCourseAreaCode"
            placeholder="请选择考场地址"
            @change="handleChange2"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="考场：" prop="examinationRoomId">
          <el-select
            v-model="addCourseForm.examinationRoomId"
            placeholder="请选择考场"
            @change="selectChange(addCourseForm.examinationRoomId)"
          >
            <el-option
              v-for="item in rooms"
              :key="item.id"
              :label="item.roomName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称：" prop="coursesName">
          <el-input v-model="addCourseForm.coursesName" />
        </el-form-item>
        <el-form-item label="课程标题：" prop="label">
          <el-input v-model="addCourseForm.label" />
        </el-form-item>
        <el-form-item label="金额：" prop="money">
          <el-input v-model="addCourseForm.money" />
        </el-form-item>
        <el-form-item label="封面：" prop="coverUrl">
          <el-upload
            class="avatar-uploader"
            action=""
            :http-request="modeUpload"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="addCourseForm.coverUrl"
              :src="addCourseForm.coverUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述：" prop="coursesDesc">
          <el-input v-model="addCourseForm.coursesDesc" />
        </el-form-item>
        <el-form-item label="是否免费：" prop="freeTag">
          <el-select
            v-model="addCourseForm.freeTag"
            placeholder="请选择是否免费"
          >
            <el-option
              v-for="item in freeTagOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效时长：" prop="effectiveTime">
          <!-- <el-date-picker
            v-model="addCourseForm.effectiveTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          >
          </el-date-picker> -->
          <el-input v-model="addCourseForm.effectiveTime" />
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="addCourseCancel">取 消</el-button>
        <el-button
          type="primary"
          @click="addCouseSubmit"
          :loading="addCoucseLoading"
          >{{ loading ? "提交中 ..." : "确 定" }}</el-button
        >
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {
  regionData,
  provinceAndCityData,
  codeToText,
  TextToCode,
} from "element-china-area-data";

export default {
  name: "Users",
  data() {
    // const checkPhone = (rule, value, callback) => {
    //   value = value.trim();
    //   let reg_tel =
    //     /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    //   if (value === "") {
    //     callback(new Error("手机号码不能为空!"));
    //   } else if (!reg_tel.test(value)) {
    //     callback(new Error("请正确填写您的手机号码!"));
    //   } else {
    //     callback();
    //   }
    // };
    // const checkNull = (rule, value, callback) => {
    //   value = value.trim();
    //   if (value === "") {
    //     callback(new Error("内容不能为空!"));
    //   } else {
    //     callback();
    //   }
    // };
    // const validatePassword = (rule, value, callback) => {
    //   value = value.trim();
    //   if (value === "") {
    //     callback(new Error("密码长度不能为空!"));
    //   } else if (value.length < 6) {
    //     callback(new Error("密码长度不能小于6位数!"));
    //   } else {
    //     callback();
    //   }
    // };
    return {
      drawer: false,
      rooms: [],
      room: "",
      // ------
      listLoading: false, // 是否显示列表加载的提示
      searchContent: "",
      user: {
        userName: "",
        password: "",
        sex: "",
        phoneNumber: "",
        userType: "",
      }, // 当前要操作的user
      dialogUserVisible: false, // 是否显示用户添加/修改的dialog
      showImport: false,
      currentUser: "",
      loading: false, // 是否正在提交请求中
      showPhoneInfo: false,
      modifyForm: {},
      Modifyid: "",
      // --------------
      current: 1, // 当前页码
      count: 4, // 每页数量
      total: 0, // 总数量
      options: provinceAndCityData,
      selectedOptions: [],
      currentAreaCode: "",
      addCourseVisible: false,
      addCourseRules: {
        addCourseAreaCode: [
          { required: true, message: "考场地址不能为空", trigger: "blur" },
        ],
        examinationRoomId: [
          { required: true, message: "考场不能为空", trigger: "blur" },
        ],
        coursesName: [
          { required: true, message: "课程名称不能为空", trigger: "blur" },
        ],
        money: [{ required: true, message: "金额不能为空", trigger: "blur" }],
        coverUrl: [
          { required: true, message: "封面不能为空", trigger: "blur" },
        ],
        coursesDesc: [
          { required: true, message: "描述不能为空", trigger: "blur" },
        ],
        freeTag: [
          { required: true, message: "是否免费不能为空", trigger: "blur" },
        ],
        effectiveTime: [
          { required: true, message: "有效时长不能为空", trigger: "blur" },
        ],
      },
      addCourseFormTitle: "",
      addCourseForm: {
        addCourseAreaCode: "",
        examinationRoomId: "",
        coursesName: "",
        money: "",
        coverUrl: "",
        coursesDesc: "",
        freeTag: "",
        effectiveTime: "",
      },
      addCoucseLoading: false,
      freeTagOptions: [
        {
          value: "0",
          label: "付费",
        },
        {
          value: "1",
          label: "免费",
        },
      ],
      formLoading: false,
      courses: [],
    };
  },

  //发请求一般情况下，我们都是在mounted去发，但是也可以在created内部去发
  created() {
    this.getCourses();
  },

  methods: {
    // async handleChange1(value) {
    //   var loc = "";
    //   // console.log("CodeToText", this.selectedOptions); //打印区域码
    //   // for (let i = 0; i < this.selectedOptions.length; i++) {
    //   //   loc += codeToText[this.selectedOptions[i]];
    //   // }
    //   const areaCode = this.addCourseForm.addCourseAreaCode[1].padEnd(6, "0");
    //   console.log("handleChange", loc, value, areaCode);
    //   const result = await this.$API.course
    //     .reqGetRoomOptions({ areaCode })
    //     .catch(() => {
    //       this.$message.error("获取考场失败");
    //     });
    //   console.log("handleChange2", result);
    //   if (result.resultCode == 200) {
    //     this.rooms = result.data;
    //   }
    // },
    async handleChange2(value) {
      const areaCode = this.addCourseForm.addCourseAreaCode[1].padEnd(6, "0");
      console.log("handleChange", value, areaCode);
      const result = await this.$API.course
        .reqGetRoomOptions({ areaCode })
        .catch(() => {
          this.$message.error("获取考场失败");
        });
      console.log("handleChange2", result);
      if (result.resultCode == 200) {
        this.rooms = result.data;
      }
    },
    selectChange(value) {
      console.log("selectChange", value, this.addCourseForm);
    },
    // 获取分页列表
    async getCourses(pages = 1) {
      this.current = pages;
      const { current, count } = this;
      this.listLoading = true;
      let params = {
        current,
        count,
        areaCode:
          this.selectedOptions.length > 0
            ? this.selectedOptions[1]?.padEnd(6, "0")
            : "445300",
        condition: this.searchContent,
      };
      console.log(233, this.selectedOptions, params);
      const result = await this.$API.course.reqGetCourses(params).catch(() => {
        this.$message.error("获取列表失败");
      });
      console.log("getCourses", result);
      if (result.resultCode == 200) {
        this.total = result.data.total;
        this.courses = result.data.record.flatMap((item) =>
          item.courses.map((courseItem) => ({
            ...courseItem,
            roomName: item.roomName,
          }))
        );
        console.log("this.courses", this.courses);
      } else {
        this.$message.error(result.msg);
      }
      this.listLoading = false;
    },

    // 处理pageSize发生改变的监听回调
    handleSizeChange(pageSize) {
      this.count = pageSize;
      this.getCourses();
    },

    //   根据输入进行搜索
    // async search() {
    //   this.getCourses();
    // },
    // 清空搜索框内容清空
    // resetForm() {
    //   if (this.searchContent == "") {
    //     if (this.searchFormFlag == true) {
    //       this.searchFormFlag = false;
    //       this.getCourses();
    //     }
    //   }
    // },
    // 清空按钮清空
    // resetSearch() {
    //   if (this.searchFormFlag == true) {
    //     this.searchContent = "";
    //     this.searchFormFlag = false;
    //     this.getCourses();
    //   } else {
    //     this.searchContent = "";
    //   }
    // },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeAvatarUpload(file) {
      const isJPG = file.type.startsWith("image/");
      // const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("只能上传图片!");
      }
      // if (!isLt2M) {
      //   this.$message.error("上传头像图片大小不能超过 2MB!");
      // }
      return isJPG;
    },
    async modeUpload(item) {
      console.log("modeUpload1", item);
      const result = await this.$API.course.reqUploadImage({
        file: item.file,
      });
      if (result.resultCode == 200) {
        console.log("modeUpload", result);
        this.addCourseForm.coverUrl = result.data;
        this.$message({
          message: "图片上传成功",
          type: "success",
        });
      } else {
        this.$message.error("图片上传失败");
      }
    },
    addOrChangeCourseHandle(row) {
      this.addCourseVisible = true;
      console.log("addOrChangeCourseHandle", row);
      if (row.id) {
        this.addCourseFormTitle = "修改课程";
        this.addCourseForm = JSON.parse(JSON.stringify(row));
        this.addCourseForm.addCourseAreaCode = this.selectedOptions;
        console.log(111, this.addCourseForm);
      } else {
        this.addCourseFormTitle = "添加课程";
      }
    },

    addCourseCancel() {
      this.$refs.addCourseForm.resetFields();
      this.addCourseForm = {
        addCourseAreaCode: "",
        examinationRoomId: "",
        coursesName: "",
        money: "",
        coverUrl: "",
        coursesDesc: "",
        freeTag: "",
        effectiveTime: "",
      };
      this.addCourseVisible = false;
    },
    addCouseSubmit() {
      this.$refs.addCourseForm.validate(async (valid) => {
        if (valid) {
          this.formLoading = true;
          let params = JSON.parse(JSON.stringify(this.addCourseForm));
          delete params.addCourseAreaCode;
          params.money = Number(params.money);
          params.effectiveTime = Number(params.effectiveTime);
          console.log("addCouseSubmit", params);
          this.$API.course
            .reqAddCourse(params)
            .then((res) => {
              if (res.resultCode == 200) {
                if (params.id) {
                  this.$message.success("修改成功!");
                } else {
                  this.$message.success("添加成功!");
                }
              } else {
                if (params.id) {
                  this.$message.error("修改失败");
                } else {
                  this.$message.error("添加失败");
                }
              }
              this.addCourseCancel();
              this.getCourses();
            })
            .catch(() => {
              if (params.id) {
                this.$message.error("修改失败");
              } else {
                this.$message.error("添加失败");
              }
            });
          this.formLoading = false;
        } else {
          return;
        }
      });
    },
    // 删除当前用户
    async removeCourse(id) {
      const result = await this.$API.course.reqRemoveCourse({ id });
      if (result.resultCode == 200) {
        this.$message.success("删除成功!");
        this.getCourses(
          this.courses.length === 1 ? this.current - 1 : this.current
        );
      } else {
        this.$message.error("删除失败");
      }
      console.log("removeCourse", result);
    },
    routerGo(row) {
      console.log("routerGo", row);
      this.$router.push({ path: "/video/list", query: { courseId: row.id } });
    },
  },
  computed: {
    userName() {
      return this.$store.state.userInfo.userName || getToken("userName");
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  .container-header {
    display: flex;
    justify-content: space-between;
  }
}

/deep/.Import {
  .item {
    margin-bottom: 5px;
    height: 44px;
    display: flex;
    align-items: center;

    .ImportSpan {
      font-size: 16px;
    }

    .uploadBtn {
      display: inline-block;
      width: 88px;
      height: 40px;
    }
  }

  // .download{

  // }
}

/deep/.el-upload-dragger {
  display: inline-block;
  width: 100%;
  height: 100%;
  border: none;
  border-radius: 4px;
}

.demo-drawer__footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-drawer__body) {
  padding: 20px !important;
  padding-top: 0px !important;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
